﻿using System;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using SimpleServiceBus.Bus;
using SimpleServiceBus.Bus.MessageManagement;
using SimpleServiceBus.Bus.MessageManagement.MessageValueProviders;
using SimpleServiceBus.Bus.Pipeline;

namespace SimpleServiceBus.Tests.Bus.MessageManagement
{
    [TestFixture]
    public class DefaultMessageTypeManagementServiceTestFixture
    {
        [Test]
        public void Register_Type_Without_Destination_And_Overwrite_With_Destination()
        {
            var mgr = new DefaultMessageTypeManagementService();
            mgr.RegisterMessageType(typeof (Message_A));
            
            Assert.IsNull(mgr.GetDestinationFor<Message_A>());
            Assert.That(mgr.GetRegisteredMessageTypes().Length, Is.EqualTo(1));
            Assert.That(mgr.GetRegisteredMessageTypes()[0], Is.EqualTo(typeof (Message_A)));
            
            mgr.RegisterMessageType(typeof (Message_A), "destination");
            
            Assert.That(mgr.GetRegisteredMessageTypes().Length, Is.EqualTo(1));
            Assert.That(mgr.GetDestinationFor<Message_A>(), Is.EqualTo("destination"));
        }

        [Test]
        public void Get_Destination_For_Message()
        {
            var mgr = new DefaultMessageTypeManagementService();
            mgr.RegisterMessageType(typeof(Message_A), "destination");

            Assert.That(mgr.GetDestinationForMessage(new Message_A()), Is.EqualTo("destination"));
        }

        [Test]
        public void ShouldCreateHeaderBindingForRegisteredProviderAndGenerateAppropriateHeaderForMessage()
        {
            //given
            var mgr = new DefaultMessageTypeManagementService();
            mgr.RegisterMessageHeaderFor<string>("a header", new NullHeaderValueProvider());
            var msg = new MessageEnvelope() { Body = "hello" };
            
            //when
            mgr.GenerateMessageHeaders(msg, null);
            
            //then
            Assert.That(msg.Headers["a header"], Is.EqualTo("hello"));

        }

        [Test]
        public void ShouldNotGenerateHeaderForMismatchedType()
        {
            //given
            var mgr = new DefaultMessageTypeManagementService();
            mgr.RegisterMessageHeaderFor<string>("a header", new NullHeaderValueProvider());
            var msg = new MessageEnvelope() { Body = 5 };

            //when
            mgr.GenerateMessageHeaders(msg, null);

            //then
            Assert.IsNull(msg.Headers["a header"]);
        }

        public class NullHeaderValueProvider : IMessageValueProvider
        {
            public string GetMessageValue(MessageEnvelope message, IMessageContext messageContext)
            {
                return message.Body.ToString();
            }
        }

    }
}
